
#include "stc8g.h"
#include "type.h"
#include "eeprom.h"
// EEPROM操作函数实现
void EEPROM_SectorErase(unsigned int addr) {
    IAP_CONTR = 0x80;   // 使能IAP
    IAP_CMD = 0x03;     // 扇区擦除命令
    IAP_ADDRH = addr >> 8;
    IAP_ADDRL = addr & 0xFF;
    IAP_TRIG = 0x5A;
    IAP_TRIG = 0xA5;
    _nop_();
    _nop_();
    IAP_CONTR = 0x00;   // 关闭IAP
}

// EEPROM字节写入
void EEPROM_ByteWrite(unsigned int addr, unsigned char dat) {
    IAP_CONTR = 0x80;   // 使能IAP
    IAP_CMD = 0x02;     // 字节编程命令
    IAP_ADDRH = addr >> 8;
    IAP_ADDRL = addr & 0xFF;
    IAP_DATA = dat;
    IAP_TRIG = 0x5A;
    IAP_TRIG = 0xA5;
    _nop_();
    _nop_();
    IAP_CONTR = 0x00;   // 关闭IAP
}

// EEPROM字节读取
unsigned char EEPROM_ByteRead(unsigned int addr) {
    unsigned char dat;
    IAP_CONTR = 0x80;   // 使能IAP
    IAP_CMD = 0x01;     // 字节读取命令
    IAP_ADDRH = addr >> 8;
    IAP_ADDRL = addr & 0xFF;
    IAP_TRIG = 0x5A;
    IAP_TRIG = 0xA5;
    _nop_();
    dat = IAP_DATA;
    IAP_CONTR = 0x00;   // 关闭IAP
    return dat;
}

// 保存用户参数到EEPROM
void SaveUserParams(UserParams *params, unsigned int baseAddr) {
    unsigned char *p = (unsigned char *)params;
    unsigned int i;
    
    // 先擦除整个扇区
    EEPROM_SectorErase(baseAddr);
    
    // 写入数据
    for(i = 0; i < sizeof(UserParams); i++) {
        EEPROM_ByteWrite(baseAddr + i, p[i]);
    }
}

// 从EEPROM读取用户参数
void LoadUserParams(UserParams *params, unsigned int baseAddr) {
    unsigned char *p = (unsigned char *)params;
    unsigned int i;
    
    for(i = 0; i < sizeof(UserParams); i++) {
        p[i] = EEPROM_ByteRead(baseAddr + i);
    }
}

